package com.leetcode.LinkedList;


class ListNode {

	 int val;
	  
	 ListNode next;
	    
	 ListNode(int x) { val = x; }
}
public class MergeTwoSortedLists {

	public static void main(String[] args) {
		
	}

	public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null&&l2==null) return null;
        if(l1==null) return l2;
        if(l2==null) return l1;
		int first=(l1.val<=l2.val&&l1!=null&&l2!=null)?l1.val:l2.val;

		ListNode ltnd=new ListNode(first);
		ListNode result=ltnd;
		if(first==l1.val) l1=l1.next;
		else l2=l2.next;
		while(l1!=null&&l2!=null){
			ltnd.next=l1.val<=l2.val?l1:l2;
			ltnd=ltnd.next;
			if(ltnd==l1) l1=l1.next;
			else l2=l2.next;
		}
		while(l1!=null){
			ltnd.next=l1;
			ltnd=ltnd.next;
			l1=l1.next;
		}
		while(l2!=null){
			ltnd.next=l2;
			ltnd=ltnd.next;
			l2=l2.next;
		}
		return result;
    }
}
